// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
const _ = db.command

let setting = null

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const managerUsers = (await db.collection('users')
    .where({
      role: _.or([_.eq('admin'), _.eq('master')])
    })
    .get()).data
  const resultList = []
  for (const user of managerUsers) {
    const newMsgCount = (await cloud.callFunction({
      name: 'chatCmd',
      data: {
        cmd: 'peekNewMsg',
        userId: user._id,
        userRole: user.role
      }
    })).result.totalNewMsgCount
    if (newMsgCount <= 0) continue
    user.newMsgCount = newMsgCount
    resultList.push(...(await sendSms([user])))
  }
  return resultList
}

function getDate() {
  const localDate = new Date()
  return (localDate.getMonth() + 1) + '月' + localDate.getDate() + '日' +
    prefixZero(localDate.getHours()) + '点'
}

function prefixZero(num) {
  return Number(num) < 10 ? ('0' + num) : num
}

async function sendSms(users) {
  const strDate = getDate()
  const resultList = []
  for (const user of users) {
    const unreadMsgFreq = (await loadSetting()).notify.unreadMsg
    if (user.msgNotify?.time && (new Date().getTime() - user.msgNotify.time < (unreadMsgFreq * 60 * 1000))) { // unreadMsgFreq分钟内只发送一条
      continue
    }
    const sendSmsTcResult = await cloud.callFunction({
      name: 'sendSmsTc',
      data: {
        templateName: "custom_msg",
        templateParamList: [strDate, user.newMsgCount + ''],
        phoneNumberList: ["+86" + user.phoneNumber],
        sessionContext: 'notify custom message'
      }
    })
    resultList.push(sendSmsTcResult)
    await updateUserMsgNotify([user])
  }
  return resultList
}

async function updateUserMsgNotify(users) {
  for (const user of users) {
    await db.collection('users').where({
        _id: user._id
      })
      .update({
        data: {
          msgNotify: {
            time: new Date().getTime()
          }
        }
      })
  }
}

async function loadSetting() {
  if (setting) return setting
  const res = await db.collection('setting')
    .limit(1)
    .get()
  return (setting = res.data[0])
}